package com.linln.wxapi;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.linln.common.enums.StatusEnum;
import com.linln.common.utils.EmojiFilterUtils;
import com.linln.common.utils.EntityBeanUtil;
import com.linln.common.utils.MD5;
import com.linln.common.utils.ResultVoUtil;
import com.linln.common.utils.ToolUtil;
import com.linln.common.vo.ResultVo;
import com.linln.modules.member.domain.AreaCount;
import com.linln.modules.member.domain.MemberAgent;
import com.linln.modules.member.domain.MemberInfo;
import com.linln.modules.member.service.AreaCountService;
import com.linln.modules.member.service.MemberAgentService;
import com.linln.modules.member.service.MemberInfoService;
import com.linln.modules.message.domain.MessageInfo;
import com.linln.modules.system.domain.Area;
import com.linln.modules.system.domain.SysSet;
import com.linln.modules.system.service.AreaService;
import com.linln.modules.system.service.SysSetService;
import com.linln.modules.tribe.domain.Tribetype;
import com.linln.wxapi.config.WxMaConfiguration;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import me.chanjar.weixin.common.error.WxErrorException;

/**
 * 微信小程序用户接口
 *
 * @author <a href="https://github.com/binarywang">Binary Wang</a>
 */
@RestController
@RequestMapping("/wx/member/{area}")
public class WxApiUserController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    
    @Autowired
    private MemberInfoService memberService;

    @Autowired
    private MemberAgentService memberAgentService;

    @Autowired
    private AreaCountService areaCountService;
    @Autowired
    private AreaService areaService;
     
     

    @Autowired
    private SysSetService sysSetService;

    
    
    /**
     * 登陆接口
     */
    @RequestMapping(value = "/login",method={RequestMethod.POST,RequestMethod.GET})
    public ResultVo login(@PathVariable String area, String code) {
        if (StringUtils.isBlank(code)) {
            return ResultVoUtil.error("code不能为空"); 
        }

         WxMaService wxService = WxMaConfiguration.getWxMaService();

        try {
            WxMaJscode2SessionResult session = wxService.getUserService().getSessionInfo(code);
            this.logger.info(session.getSessionKey());
            this.logger.info(session.getOpenid());
             //TODO 可以增加自己的逻辑，关联业务相关数据
           	 return ResultVoUtil.success(session);

        } catch (WxErrorException e) {
            this.logger.error(e.getMessage(), e);
            return ResultVoUtil.error("接口异常"); 
        }
    }

    /**
     * <pre>
     * 获取用户信息接口
     * </pre>
     */
    @RequestMapping(value = "/info",method={RequestMethod.POST,RequestMethod.GET})

    public ResultVo info(@PathVariable String area, String sessionKey,
                       String signature, String rawData, String encryptedData, String iv) throws WxErrorException {
        WxMaService wxService = WxMaConfiguration.getWxMaService();

        // 用户信息校验
        if (!wxService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
             return ResultVoUtil.error("校验失败"); 
        }
        // 解密用户信息
        WxMaUserInfo userInfo = wxService.getUserService().getUserInfo(sessionKey, encryptedData, iv);
        //将用户信息存储到数据库
        if(userInfo!=null) {
        MemberInfo member=memberService.getByOpenId(userInfo.getOpenId());
        if(member==null) {
        member=new MemberInfo();
        member.setCity(userInfo.getCity());
        member.setOpenid(userInfo.getOpenId());
        member.setHeadimg(userInfo.getAvatarUrl());
        member.setRegisterDate(new Date());
        member.setArea(area);
        member.setMoney(0d);        
        member.setNickname(EmojiFilterUtils.filterEmoji(userInfo.getNickName()));         
        member.setScore(0);
        member.setSessionKey(sessionKey);
        member.setSignature(signature);
        member.setRawData(rawData);
        member.setAllmoney(0d);
        member=memberService.save(member);
     	 return ResultVoUtil.success(member);
       }else {
          return ResultVoUtil.success(member);
        }
       }else {
        	 return ResultVoUtil.error("异常"); 
       }

    }


    /**
     * <pre>
     * 获取用户信息接口
     * </pre>
     */
    @RequestMapping(value = "/infoV2",method={RequestMethod.POST,RequestMethod.GET})

    public ResultVo infoV2(@PathVariable String area, String sessionKey,
                         String signature, String rawData, String encryptedData, String iv,String code) throws WxErrorException {
        WxMaService wxService = WxMaConfiguration.getWxMaService();
        WxMaJscode2SessionResult session = wxService.getUserService().getSessionInfo(code);
        sessionKey = session.getSessionKey();
        String openid = session.getOpenid();
        String unionid = session.getUnionid();

        // 用户信息校验
        if (!wxService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
            return ResultVoUtil.error("校验失败");
        }
        if (StringUtils.isBlank(code)) {
            return ResultVoUtil.error("code不能为空");
        }
        // 解密用户信息
        WxMaUserInfo userInfo = wxService.getUserService().getUserInfo(sessionKey, encryptedData, iv);
        userInfo.setOpenId(openid);
        userInfo.setUnionId(unionid);

        //将用户信息存储到数据库
        if(userInfo!=null) {
            MemberInfo member=memberService.getByOpenId(userInfo.getOpenId());
            if(member==null) {
                member=new MemberInfo();
                member.setCity(userInfo.getCity());
                member.setOpenid(userInfo.getOpenId());
                member.setHeadimg(userInfo.getAvatarUrl());
                member.setRegisterDate(new Date());
                member.setArea(area);
                member.setMoney(0d);
                member.setNickname(EmojiFilterUtils.filterEmoji(userInfo.getNickName()));
                member.setScore(0);
                member.setSessionKey(sessionKey);
                member.setSignature(signature);
                member.setRawData(rawData);
                member.setAllmoney(0d);
                member=memberService.save(member);
                return ResultVoUtil.success(member);
            }else {
                member.setSessionKey(sessionKey);
                member.setSignature(signature);
                member.setRawData(rawData);
                return ResultVoUtil.success(member);
            }
        }else {
            return ResultVoUtil.error("异常");
        }

    }

    /**
     * <pre>
     * 获取用户绑定手机号信息
     * </pre>
     */
     @RequestMapping(value = "/phone",method={RequestMethod.POST,RequestMethod.GET})

    public ResultVo phone(@PathVariable String area,String openid, String sessionKey, String signature,
                        String rawData, String encryptedData, String iv) {
         WxMaService wxService = WxMaConfiguration.getWxMaService();
        // 用户信息校验
        if (!wxService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
             return ResultVoUtil.error("校验失败"); 

        }

        // 解密
        WxMaPhoneNumberInfo phoneNoInfo = wxService.getUserService().getPhoneNoInfo(sessionKey, encryptedData, iv);
        //将用户手机号存入数据库
        if(phoneNoInfo!=null) {
        	MemberInfo memberphone=memberService.getByMobile(phoneNoInfo.getPhoneNumber());
            MemberInfo member=memberService.getByOpenId(openid);
            if(member!=null) {
            	if(member.getMobile()!=null && member.getMobile().equals(phoneNoInfo.getPhoneNumber())) {
                    return ResultVoUtil.error("手机号已注册，不能绑定"); 
            	}
            	member.setMobile(phoneNoInfo.getPhoneNumber());
            	memberService.save(member);
            	}
            }
   	 return ResultVoUtil.success(phoneNoInfo);

     }
     
     
     /**
      * 申请成为运营商
       */
     @RequestMapping(value="/apply",method={RequestMethod.POST,RequestMethod.GET})
     @ResponseBody
     public ResultVo save( MemberAgent memberInfo,Long memberId,String province,String city,String county) {
    	 
    	 ExampleMatcher matcher = ExampleMatcher.matching();
    	 MemberAgent memberAgentInfo=new MemberAgent();
    	 memberAgentInfo.setStatus(null);
    	 memberAgentInfo.setArea(county);  
	     Example<MemberAgent> example = Example.of(memberAgentInfo, matcher);
	     List<MemberAgent> memberoldNew=memberAgentService.getList(example);
	     if(memberoldNew!=null && memberoldNew.size()>0) {
	    	 System.out.println("有信息");
	    	 //代表已经存在
	    	 MemberAgent memberold=memberoldNew.get(0);
	    	 Byte statusinfo=0;
		     byte a=0;
	    	 if(memberold.getStatus().equals(StatusEnum.OK.getCode()) || (memberold.getStatus().byteValue()==a && memberold.getPayStatus()==1)) {
	     			return ResultVoUtil.error("该地区已被申请");      	     			
	     		}
	    	  /*else if(memberold.getStatus().equals(StatusEnum.FREEZED.getCode())){
	     	         return ResultVoUtil.success("改地区已被冻结",memberold);
	     		}else if(memberold.getStatus().equals(StatusEnum.DELETE.getCode())){
	     			memberold.setStatus(StatusEnum.DELETE.getCode());
	     			memberAgentService.updateAgentStatus(2, memberold.getId());
	    	         return ResultVoUtil.success("已被停用",memberold);	    	         
	    		}else if(memberold.getStatus().equals(statusinfo)){
	    			 if(memberold.getPayStatus().intValue()==1) {
		     	         return ResultVoUtil.success("该区域已被其他代理商申请",memberold);
	    			 }*/
	    	 else {
				    MemberInfo member=new MemberInfo();
				    //进行update操作
			        member.setId(memberId);
			     	memberold.setMember(member);
			     	memberold.setCreateDate(new Date());
			     	memberold.setUpdateDate(new Date());
			     	memberold.setArea(county);
			     	memberold.setAllmoney(0D);
			     	memberold.setCurmoney(0d);
			     	memberold.setPayStatus(1);
			     	memberold.setAreaname(city);
			     	memberold.setOrderId(ToolUtil.getRandomString(32));
			     	byte f=0;
			     	memberold.setStatus(f);
			     	memberold.setPayStatus(0);
			     	SysSet set=sysSetService.getById(1L);
			     	memberold.setAgentMoney(Double.valueOf(set.getValue()));
			        MemberAgent agentold=memberAgentService.save(memberold);
			        System.out.println("进来了--》"+agentold.getOrderId());
     	            return ResultVoUtil.success("申请成功等待审核",agentold);

	    			 
	     		}  
	     }

     	/*MemberAgent memberold=memberAgentService.getByMemberIdAndArea(memberId, county);
     	if(memberold!=null&& memberold.getId()>0) {
     		if(memberold.getStatus().equals(StatusEnum.OK.getCode())) {
     			return ResultVoUtil.error("该地区已被申请");      	     			
     		}else if(memberold.getStatus().equals(StatusEnum.FREEZED.getCode())){
     	         return ResultVoUtil.success("申请成功等待审核",memberold);
     		}else if(memberold.getStatus().equals(StatusEnum.DELETE.getCode())){
     			memberold.setStatus(StatusEnum.FREEZED.getCode());
     			memberAgentService.updateAgentStatus(2, memberold.getId());
    	         return ResultVoUtil.success("已被下架",memberold);
    		}     	
     	}*/
     	MemberInfo member=new MemberInfo();
        member.setId(memberId);
     /*	MemberInfo memberNew=memberService.getById(memberId);
      * String md5password=MD5.getMD5String("123456");
     	memberNew.setPassword(md5password);
     	memberNew.setIsagent(1);
     	memberService.save(memberNew);
     */
     	memberInfo.setMember(member);
     	memberInfo.setCreateDate(new Date());
     	memberInfo.setUpdateDate(new Date());
     	memberInfo.setArea(county);
     	memberInfo.setAllmoney(0D);
     	memberInfo.setCurmoney(0d);
      	memberInfo.setAreaname(city);
     	memberInfo.setOrderId(ToolUtil.getRandomString(32));
     	byte a=0;
     	memberInfo.setStatus(a);
     	memberInfo.setPayStatus(0);
     	SysSet set=sysSetService.getById(1L);
     	memberInfo.setAgentMoney(Double.valueOf(set.getValue()));
         // 复制保留无需修改的数据
         if (memberInfo.getId() != null) {
             MemberAgent beMemberInfo = memberAgentService.getById(memberInfo.getId());
             EntityBeanUtil.copyProperties(beMemberInfo, memberInfo);
         }
         // 保存数据
         MemberAgent agent=memberAgentService.save(memberInfo);
         AreaCount areacount=areaCountService.findByArea(agent.getArea());
     	if(areacount==null) {
     		areacount=new AreaCount();
     		areacount.setArea(agent.getArea());
     		areacount.setMessage_shouFabunum(20000);
     		areacount.setMessage_shouReadnum(200000);
     		areacount.setMessage_shouShareunum(1000);
     		areaCountService.save(areacount);
     	}
         return ResultVoUtil.success("申请成功等待审核",agent);
     }

     
    /**
      * 获取设置
      */
     @RequestMapping(value="/getSysSet",method={RequestMethod.POST,RequestMethod.GET})
     @ResponseBody
     public ResultVo getSysSet() {
    	 SysSet set=sysSetService.getById(1L);
         return ResultVoUtil.success(set);
     }
     
     /**
      * 判断是否是代理商
      */
     @RequestMapping(value="/validArea",method={RequestMethod.POST,RequestMethod.GET})
     @ResponseBody
     public ResultVo validArea(String county) {
    	 MemberAgent memberInfo=new MemberAgent();
    	// 创建匹配器，进行动态查询匹配
         ExampleMatcher matcher = ExampleMatcher.matching();
         memberInfo.setArea(county);
         // 获取数据列表
         Example<MemberAgent> example = Example.of(memberInfo, matcher);
    	 
    	List<MemberAgent> list= memberAgentService.getList(example);
     	if(list!=null&& list.size()>0) {
            return ResultVoUtil.success("已被申请");

     	}
			return ResultVoUtil.error("未被申请");      	     			

     }
     
     
     /**
      * 修改默认区域
      * @param valid 验证对象
      */
     @RequestMapping(value="/updateArea",method={RequestMethod.POST,RequestMethod.GET})
     @ResponseBody
     public ResultVo updateArea(String county,String countyname,Long memberId) {
    	 MemberInfo memberInfo=new MemberInfo();
    	 if(memberId==null) {
    		 return ResultVoUtil.error(300,"用户未登录");      	     			
    	 }
    	// 创建匹配器，进行动态查询匹配
         memberInfo.setId(memberId);
         memberInfo=memberService.getById(memberId);
         memberInfo.setArea(county);
         memberInfo.setAreaname(countyname); 
         memberService.save(memberInfo);
		 return ResultVoUtil.SAVE_SUCCESS;     	     			

     }


    /**
     * 判断我是不是当前区域的代理商
     */
    @RequestMapping(value="/agentMyArea",method={RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public ResultVo agentMyArea(@PathVariable String area,Long memberId) {
        Map<String,Object> map=new HashMap<String,Object>();
        MemberAgent memberAgent=memberAgentService.getByMemberIdAndArea(memberId,area);
        if(memberAgent!=null && memberAgent.getId()>0){
            map.put("isagent",1);
        }else{
            map.put("isagent",0);

        }
        return ResultVoUtil.success(map);

    }

}

